import { request } from "../../utils/request"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartCount: 0, //购物车商品数
    cartList: [], //购物车列表
    allChecked: false, //全选
    totalPrice: 0, //合计总价
    totalNum: 0, //需要结算的商品数
    showLogin: false //控制登录模态框
  },

  /**
   * 加载购物车数据
   */
  async loadCartInfo() {
    const { token } = wx.getStorageSync("user")
    const res = await request({ url: "/cart/listCart/", method: "GET", header: { "Authorization": token } })
    if (res.data.state === 0) {
      let cart = res.data.data
      this.setData({
        cartList: cart
      })
      //计算全选，合计，结算商品数
      this.calcTotal(cart)
    }
  },

  /**
   * 计算全选，合计，结算商品数
   */
  calcTotal(cart) {
    let cartCount = 0
    let allChecked = true
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      cartCount = v.num + cartCount
      if (v.checked) {
        totalPrice = totalPrice + v.num * v.price
        totalNum = totalNum + v.num
      } else {
        allChecked = false;
      }
    });
    this.setData({
      cartCount: cartCount,
      allChecked: allChecked,
      totalPrice: totalPrice,
      totalNum: totalNum
    })
  },

  /**
   * 处理购物车商品的复选框事件
   */
  async handlerItemChange(option) {
    //获取被点击的商品id
    const pid = option.currentTarget.dataset.id
    //获取当前购物车中被点击的购物项的选中状态
    let cart = this.data.cartList
    const index = cart.findIndex(v => v.id === pid)
    const checkedState = !cart[index].checked;
    //设置请求数据
    let changeData = {
      productId: pid,
      checked: checkedState
    }
    //发送请求修改购物项选中状态
    const { token } = wx.getStorageSync("user")
    const res = await request({ url: "/cart/changeChecked/", method: "POST", header: { "Authorization": token }, data: changeData })
    if (res.data.state === 0) {
      //设置购物车列表中当前商品选中的状态
      cart[index].checked = checkedState
      //刷新购物车数据
      this.refreshCartData(cart)
    }
  },

  /**
   * 处理全选事件
   */
  async handlerAllChange() {
    //获取当前全选状态相反的情况
    const allChecked = !this.data.allChecked
    //发送请求更改购物车选中状态
    const { token } = wx.getStorageSync("user")
    const res = await request({ url: `/cart/batchChangeChecked/${allChecked}`, method: "POST", header: { "Authorization": token } })
    if (res.data.state === 0) {
      //设置购物车列表中所有商品选中的状态
      let cart = this.data.cartList
      cart.forEach(v => v.checked = allChecked)
      //刷新购车数据
      this.refreshCartData(cart)
    }
  },

  /**
   * 处理购物车商品数量增减事件
   */
  async handlerItemNumEdit(option) {
    //获取当前被操作的商品id和操作方式
    let productId = option.currentTarget.dataset.id
    let operation = option.currentTarget.dataset.operation
    //找到当前被操作的商品在购物车列表中的索引下标
    let cart = this.data.cartList
    let index = cart.findIndex(v => v.id === productId)
    const { token } = wx.getStorageSync("user")
    //如果是增加数量操作
    if (operation === "add") {
      const changeData = {
        productId: productId,
        operation: operation,
        num: 1
      }
      const res = await request({ url: "/cart/changeNum/", method: "POST", header: { "Authorization": token }, data: changeData })
      if (res.data.state === 0) {
        cart[index].num += 1
        //刷新购物车数据
        this.refreshCartData(cart)
      }
      return
    }

    //如果是减少数量操作
    if (operation === "decrease") {
      //如果当前购买的数量大于1，做数量减少，否则是提示删除
      if (cart[index].num > 1) {
        const changeData = {
          productId: productId,
          operation: operation,
          num: 1
        }
        const res = await request({ url: "/cart/changeNum/", method: "POST", header: { "Authorization": token }, data: changeData })
        if (res.data.state === 0) {
          cart[index].num -= 1
          //刷新购物车数据
          this.refreshCartData(cart)
        }
      } else {
        wx.showModal({
          title: "温馨提示",
          content: "确定要从购物车删除此商品吗？",
          success: async res => {
            if (res.confirm) {
              const res = await request({ url: `/cart/deleteToCart/${productId}`, method: "POST", header: { "Authorization": token } })
              if (res.data.state === 0) {
                cart.splice(index, 1)
                //刷新购物车数据
                this.refreshCartData(cart)
              }
            }
          }
        })
      }
      return
    }
  },

  /**
   * 刷新购物车数据
   */
  refreshCartData(cart) {
    this.setData({
      cartList: cart
    })
    //计算全选，合计，结算商品数
    this.calcTotal(cart)
  },

  /**
   * 结算事件处理
   */
  handlerBalance(option) {
    if (this.data.totalNum === 0) {
      wx.showToast({
        title: "您还没有需要结算的商品",
        icon: "none"
      })
      return
    }
    //跳转到结算页,orderType=0代表购买类型为购物车购买
    wx.navigateTo({
      url: "/pages/pay/pay?orderType=0"
    })
  },

  /**
   * 处理登录授权
   * @param {*} event 
   */
  handlerLoginChange(event) {
    const newVal = event.detail.newVal;
    if (newVal) {
      // 刷新页面
      this.onShow()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //检查用户是否有授权登录
    const user = wx.getStorageSync("user")
    if (user) {
      this.setData({
        showLogin: false
      })
      //获取购物车列表
      this.loadCartInfo()
    } else {
      //清空当前页面数据，并弹出登录提示框
      this.setData({
        showLogin: true,
        cartCount: 0,
        cartList: [],
        allChecked: false,
        totalPrice: 0,
        totalNum: 0,
      })
    }
  }
})